package com.starmark.core.framework.advice;

import com.starmark.core.framework.response.Response;
import com.starmark.core.framework.response.SuccessResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@Order(-1)
@RestControllerAdvice
@SuppressWarnings("rawtypes")
public class JsonResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    protected final Logger logger = LoggerFactory.getLogger(
            JsonResponseBodyAdvice.class);

    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class clazz,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if(request.getHeaders().containsKey("feign-header")){
            return object;
        }
        String uri = request.getURI().toString();
        if (uri.endsWith("configuration/ui") || uri.endsWith("swagger-resources") || uri.endsWith("v2/api-docs")
                || uri.endsWith("configuration/security")) return object;
        if (object instanceof Response) {
            return object;
        }

        return new SuccessResponseData(object);
    }

    @SuppressWarnings({"unchecked"})
    public boolean supports(MethodParameter methodParameter, Class clazz) {
        return clazz.isAssignableFrom(MappingJackson2HttpMessageConverter.class);
    }

}